package com.example.project.controller.system;

import java.sql.Timestamp;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.project.core.controller.BaseController;
import com.example.project.core.domain.AjaxResult;
import com.example.project.core.text.Convert;
import com.example.project.entity.UserOnline;
import com.example.project.enums.OnlineStatus;
import com.example.project.mapper.UserOnlineMapper;
import com.example.project.service.SystemConfigService;
import com.example.project.utils.ServletUtils;
import com.example.project.utils.ShiroUtils;
import com.example.project.utils.StringUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@Controller
public class LoginController extends BaseController {

	/**
	 * 是否开启记住我功能
	 */
	@Value("${shiro.rememberMe.enabled: false}")
	private boolean rememberMe;

	@Autowired
	private SystemConfigService configService;
	
	@Autowired
	private UserOnlineMapper userOnlineMapper;

	@GetMapping("/login")
	public String login(HttpServletRequest request, HttpServletResponse response, ModelMap mmap) {
		// 如果是Ajax请求，返回Json字符串。
		if (ServletUtils.isAjaxRequest(request)) {
			return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
		}
		// 是否开启记住我
		mmap.put("isRemembered", rememberMe);
		// 是否开启用户注册
		mmap.put("isAllowRegister", Convert.toBool(configService.selectConfigByKey("sys.account.registerUser"), false));
		return "login";
	}

	@PostMapping("/login")
	@ResponseBody
	public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe) {
		UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			// 保存会话信息到数据库
			UserOnline online = new UserOnline();
			online.setSessionId(subject.getSession().getId().toString());
			online.setLoginName(username);
			online.setIpaddr(ShiroUtils.getIp());
			online.setBrowser(ServletUtils.getBrowser());
			online.setOs(ServletUtils.getOs());
			online.setStatus(OnlineStatus.on_line);
			online.setStartTimestamp(new Timestamp(System.currentTimeMillis()));
			online.setLastAccessTime(new Timestamp(System.currentTimeMillis()));
			online.setExpireTime(subject.getSession().getTimeout());
			userOnlineMapper.saveOnline(online);
			return success();
		} catch (AuthenticationException e) {
			String msg = "用户或密码错误";
			if (StringUtils.isNotEmpty(e.getMessage())) {
				msg = e.getMessage();
			}
			return error(msg);
		}
	}

	@GetMapping("/unauth")
	public String unauth() {
		return "error/unauth";
	}
}
